import { getShopIndex } from "../../../api/shop"

Page({
  data: {
    member_id: '',
    city_name: '',
    goods_name: '',
    sort_data: 1,
    goodsList: [],
    page: 1,
    pageSize: 10,
    total: 0,
    showTopBtn: false,
    loadTip: '',
    showLoading: false
  },
  onLoad(options) {
    this.setData({
      member_id: options.member_id,
      goods_name: options.goods_name,
      city_name: options.city_name || ''
    });
    this.getList();
  },
  onReachBottom() {
    // 页面拉到底部
    const { goodsList, total } = this.data;
    if (goodsList.length < total) {
      this.setData({
        showLoading: true
      })
      this.getList(true);
    } else if (total > 4) {
      this.setData({
        loadTip: '没有更多数据了'
      })
    }
  },
  getList(flag) {
    // flag为true则加载更多
    const { member_id, city_name, goods_name, sort_data, page, pageSize } = this.data;
    getShopIndex({
      member_id, city_name, goods_name, sort_data, page: flag ? page + 1 : 1, pageSize
    }).then(res => {
      let list = [];
      if (flag) {
        this.setData({
          showLoading: false
        })
        list = [...this.data.goodsList, ...res.data];
      } else {
        list = res.data;
      }
      this.setData({
        goodsList: list,
        total: res.total,
        page: res.current_page
      })
    })
  },
  getSortList(sortType) {
    this.setData({
      sort_data: sortType
    });
    this.getList();
  },
  onPageScroll(e) {
    this.setData({
      showTopBtn: e.scrollTop > 600
    })
  },
  bindInput(e) {
    this.setData({
      goods_name: e.detail.value,
    });
  },
  selectCity() {
    const that = this;
    my.getLocation({
      type: 1,
      success(res) {
        that.setData({
          city_name: res.city.slice(0, 2)
        })
        my.chooseCity({
          showLocatedCity: true,
          showHotCities: true,
          setLocatedCity: true,
          success: (res) => {
            that.setData({
              city_name: res.city
            })
          },
        });
      },
    });
  },
  clearInput() {
    this.setData({
      goods_name: ''
    });
    this.getList();
  },
  search() {
    this.getList();
  }
});
